﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.IO.Compression;
using System.Runtime.Serialization;
using System.Xml;

namespace ZX.Common
{
    public class ZipCompress
    {
        public static byte[] Compress(byte[] array)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                GZipStream gZipStream = new GZipStream(stream, CompressionMode.Compress);
                gZipStream.Write(array, 0, array.Length);
                gZipStream.Close();
                return stream.ToArray();
            }
        }

        public static byte[] Decompress(byte[] array)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                GZipStream gZipStream = new GZipStream(new MemoryStream(array), CompressionMode.Decompress);
                byte[] b = new byte[4096];
                while (true)
                {
                    int n = gZipStream.Read(b, 0, b.Length);
                    if (n > 0)
                        stream.Write(b, 0, n);
                    else
                    {
                        if (stream.Length == 0)
                            throw new Exception("Cannot read from GZipStream.");
                        else
                            break;
                    }
                }
                gZipStream.Close();

                return stream.ToArray();
            }
        }

 
        public static byte[] GetCompressByteFromXml(string strXml)
        {
            return ZipCompress.Compress(Encoding.Unicode.GetBytes(strXml));
        }
    }
}
